package com.dragon.app.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalTime;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

/**
 * @Author: longtao
 * @Date: 2019/5/28
 * @Version: 1.0
 * @Description:
 */
public class Test {

    public static void main(String[] args) throws IOException, InterruptedException {

        Buffer buffer = ByteBuffer.allocate(1024);

        Path path = Paths.get("");

        FileChannel fileChannel;


        ServerSocketChannel sschannel = ServerSocketChannel.open();
        sschannel.configureBlocking(false);
        sschannel.bind(new InetSocketAddress(9090));

        Selector selector = Selector.open();
        sschannel.register(selector, SelectionKey.OP_ACCEPT);


        while (selector.select() > 0) {
            System.out.println("selector in...");

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                System.out.println("iterator in...");
                SelectionKey selectionKey = iterator.next();

                if (selectionKey.isAcceptable()) {
                    System.out.println("isAcceptable in...");
                    SocketChannel schannel = sschannel.accept();
                    schannel.configureBlocking(false);
                    schannel.register(selector, SelectionKey.OP_READ);
                } else if (selectionKey.isReadable()) {
                    System.out.println("isReadable in...");
                    SocketChannel schannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    //schannel.read(byteBuffer);
                    int len = 0;
                    while ((len = schannel.read(byteBuffer)) > 0) {
                        byteBuffer.flip();
                        System.out.println(LocalTime.now() + " : " + new String(byteBuffer.array(), 0, len));
                        byteBuffer.clear();
                    }
                } if (selectionKey.isWritable()){
                    System.out.println("isWritable in...");
                }

                iterator.remove();

                System.out.println("iterator end1...");
            }
        }


    }


}
